package com.adk.backend.service.impl;

import com.adk.backend.entity.LxVndCheckDetails;
import com.adk.backend.entity.LxVndCheckList;
import com.adk.backend.entity.LxVndList;
import com.adk.backend.mapper.VndCheckDetailsMapper;
import com.adk.backend.mapper.VndCheckListMapper;
import com.adk.backend.mapper.VndListMapper;
import com.adk.backend.service.SpssService;
import com.adk.backend.util.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SPSS（供应商对账）服务实现类
 */
@Slf4j
@Service
public class SpssServiceImpl implements SpssService {
    
    @Autowired
    private VndListMapper vndListMapper;
    
    @Autowired
    private VndCheckListMapper vndCheckListMapper;
    
    @Autowired
    private VndCheckDetailsMapper vndCheckDetailsMapper;
    
    @Autowired
    private ExcelUtil excelUtil;
    
    @Override
    public List<LxVndList> getVndListForSpss(Integer type) {
        QueryWrapper<LxVndList> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", 0);
        
        // 如果type为null或0，则查询所有类型（type != 3，排除船公司）
        if (type == null || type == 0) {
            wrapper.ne("type", 3);
        } else {
            wrapper.eq("type", type);
        }
        
        wrapper.orderByDesc("id");
        return vndListMapper.selectList(wrapper);
    }
    
    @Override
    public List<Map<String, Object>> getVndCheckList(Long vndId) {
        Map<String, Object> params = new HashMap<>();
        params.put("vndId", vndId);
        return vndCheckListMapper.selectVndCheckListWithVnd(params);
    }
    
    @Override
    public List<LxVndCheckDetails> getVndCheckDetails(Long vclId) {
        return vndCheckDetailsMapper.selectByVclId(vclId);
    }
    
    @Override
    public Map<String, Object> getVndCheckListInfo(Long vclId) {
        LxVndCheckList vcl = vndCheckListMapper.selectById(vclId);
        if (vcl == null) {
            return null;
        }
        
        LxVndList vnd = vndListMapper.selectById(vcl.getVndId());
        
        Map<String, Object> result = new HashMap<>();
        result.put("vndCheckList", vcl);
        result.put("vndName", vnd != null ? vnd.getVndName() : "");
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveVndCheckDetails(LxVndCheckDetails details, Integer userId) {
        // 计算总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        if (details.getPrice() != null && details.getTotalGw() != null) {
            totalAmount = details.getPrice().multiply(details.getTotalGw());
        }
        if (details.getBgFee() != null) {
            totalAmount = totalAmount.add(details.getBgFee());
        }
        if (details.getZfFee() != null) {
            totalAmount = totalAmount.add(details.getZfFee());
        }
        if (details.getDkFee() != null) {
            totalAmount = totalAmount.subtract(details.getDkFee());
        }
        details.setTotalAmount(totalAmount);
        
        int currentTime = (int) (System.currentTimeMillis() / 1000);
        
        if (details.getId() != null && details.getId() > 0) {
            // 更新
            LxVndCheckDetails existing = vndCheckDetailsMapper.selectById(details.getId());
            if (existing == null) {
                return false;
            }
            if (existing.getIsCheck() != null && existing.getIsCheck() == 1) {
                // 已确认，不能编辑
                return false;
            }
            
            vndCheckDetailsMapper.updateById(details);
        } else {
            // 新增
            if (details.getAddTime() == null) {
                details.setAddTime(currentTime);
            }
            if (details.getAddUid() == null) {
                details.setAddUid(userId);
            }
            vndCheckDetailsMapper.insert(details);
        }
        
        // 更新对账列表的统计信息
        updateVndCheckListSummary(details.getVclId());
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteVndCheckDetails(Long id) {
        LxVndCheckDetails details = vndCheckDetailsMapper.selectById(id);
        if (details == null) {
            return false;
        }
        
        if (details.getIsCheck() != null && details.getIsCheck() == 1) {
            // 已确认，不能删除
            return false;
        }
        
        Long vclId = details.getVclId();
        vndCheckDetailsMapper.deleteById(id);
        
        // 更新对账列表的统计信息
        updateVndCheckListSummary(vclId);
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean lockVndCheckDetails(Long id, boolean lock) {
        LxVndCheckDetails details = vndCheckDetailsMapper.selectById(id);
        if (details == null) {
            return false;
        }
        
        details.setIsCheck(lock ? 1 : 0);
        return vndCheckDetailsMapper.updateById(details) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateVndCheckListStatus(Long id, Integer status, BigDecimal paidAmount, Integer userId) {
        LxVndCheckList vcl = vndCheckListMapper.selectById(id);
        if (vcl == null) {
            return false;
        }
        
        vcl.setStatus(status);
        if (paidAmount != null) {
            vcl.setPaidAmount(paidAmount);
        }
        int currentTime = (int) (System.currentTimeMillis() / 1000);
        vcl.setPaidTime(currentTime);
        vcl.setPaidAddUid(userId);
        vcl.setPaidAddTime(currentTime);
        
        return vndCheckListMapper.updateById(vcl) > 0;
    }
    
    /**
     * 更新对账列表的统计信息
     */
    private void updateVndCheckListSummary(Long vclId) {
        Map<String, Object> summary = vndCheckDetailsMapper.selectSummaryByVclId(vclId);
        if (summary != null) {
            LxVndCheckList vcl = vndCheckListMapper.selectById(vclId);
            if (vcl != null) {
                Integer totalQty = ((Number) summary.get("total_qty")).intValue();
                BigDecimal totalAmount = (BigDecimal) summary.get("total_amount");
                
                vcl.setTotalNums(totalQty);
                vcl.setTotalAmount(totalAmount);
                vndCheckListMapper.updateById(vcl);
            }
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public LxVndCheckList createVndCheckList(Long vndId, String fMonth, Integer userId) {
        // 检查是否已存在
        if (checkVndCheckListExists(vndId, fMonth)) {
            throw new RuntimeException("该月份的对账记录已存在");
        }
        
        LxVndCheckList vcl = new LxVndCheckList();
        vcl.setVndId(vndId);
        vcl.setFMonth(fMonth);
        
        // 将月份字符串转换为时间戳（格式：YYYY-MM）
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            Date date = sdf.parse(fMonth);
            vcl.setFMonthInt((int) (date.getTime() / 1000));
        } catch (ParseException e) {
            log.error("解析月份失败: {}", fMonth, e);
            throw new RuntimeException("月份格式错误，应为YYYY-MM格式");
        }
        
        vcl.setTotalNums(0);
        vcl.setTotalAmount(BigDecimal.ZERO);
        vcl.setStatus(1); // 默认状态：未付
        vcl.setPaidAmount(BigDecimal.ZERO);
        
        int currentTime = (int) (System.currentTimeMillis() / 1000);
        vcl.setAddTime(currentTime);
        vcl.setAddUid(userId);
        
        vndCheckListMapper.insert(vcl);
        return vcl;
    }
    
    @Override
    public boolean checkVndCheckListExists(Long vndId, String fMonth) {
        QueryWrapper<LxVndCheckList> wrapper = new QueryWrapper<>();
        wrapper.eq("vnd_id", vndId);
        wrapper.eq("f_month", fMonth);
        return vndCheckListMapper.selectCount(wrapper) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> importExcel(Long vclId, Integer type, MultipartFile file, Integer userId) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", "");
        result.put("imported", 0);
        result.put("skipped", 0);
        
        try {
            // 验证对账列表是否存在
            LxVndCheckList vcl = vndCheckListMapper.selectById(vclId);
            if (vcl == null) {
                result.put("message", "对账列表不存在");
                return result;
            }
            
            // 读取Excel文件
            List<List<String>> data = excelUtil.readExcel(file);
            
            if (data == null || data.size() < 2) {
                result.put("message", "Excel文件为空或格式不正确");
                return result;
            }
            
            int currentTime = (int) (System.currentTimeMillis() / 1000);
            String errMsg = null;
            int imported = 0;
            int skipped = 0;
            
            // 第一遍检查：验证数据有效性
            for (int k = 1; k < data.size(); k++) {
                List<String> row = data.get(k);
                if (row == null || row.size() < 5) {
                    continue;
                }
                
                // 检查必填字段
                String obDateStr = row.size() > 0 ? row.get(0).trim() : "";
                String blNo = row.size() > 1 ? row.get(1).trim() : "";
                String qtyStr = row.size() > 2 ? row.get(2).trim() : "";
                String totalGwStr = row.size() > 3 ? row.get(3).trim() : "";
                String priceStr = row.size() > 4 ? row.get(4).trim() : "";
                
                if (obDateStr.isEmpty()) {
                    errMsg = "行 " + (k + 1) + ", 出货日期 为空.";
                    break;
                }
                if (blNo.isEmpty()) {
                    errMsg = "行 " + (k + 1) + ", " + (type == 1 || type == 2 ? "订单号" : "柜号") + " 为空.";
                    break;
                }
                if (qtyStr.isEmpty() || Integer.parseInt(qtyStr) < 1) {
                    errMsg = "行 " + (k + 1) + ", 件数 小于1.";
                    break;
                }
                if (totalGwStr.isEmpty() || Double.parseDouble(totalGwStr) < 1) {
                    errMsg = "行 " + (k + 1) + ", 重量 不太对.";
                    break;
                }
                if (priceStr.isEmpty() || Double.parseDouble(priceStr) < 1) {
                    errMsg = "行 " + (k + 1) + ", 单价 不太对.";
                    break;
                }
                
                // 检查订单号是否已存在
                QueryWrapper<LxVndCheckDetails> wrapper = new QueryWrapper<>();
                wrapper.eq("bl_no", blNo);
                if (vndCheckDetailsMapper.selectCount(wrapper) > 0) {
                    errMsg = "行 " + (k + 1) + ", 订单号: " + blNo + " 已存在,不允许重复导入.";
                    break;
                }
            }
            
            if (errMsg != null) {
                result.put("message", errMsg);
                return result;
            }
            
            // 第二遍：导入数据
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String successMsg = "导入成功.";
            
            for (int k = 1; k < data.size(); k++) {
                List<String> row = data.get(k);
                if (row == null || row.size() < 5) {
                    continue;
                }
                
                String obDateStr = row.get(0).trim();
                String blNo = row.get(1).trim();
                int qty = Integer.parseInt(row.get(2).trim());
                double totalGw = Double.parseDouble(row.get(3).trim());
                double price = Double.parseDouble(row.get(4).trim());
                
                // 检查订单号是否已存在
                QueryWrapper<LxVndCheckDetails> wrapper = new QueryWrapper<>();
                wrapper.eq("bl_no", blNo);
                if (vndCheckDetailsMapper.selectCount(wrapper) > 0) {
                    successMsg += " 跳过订单号: " + blNo;
                    skipped++;
                    continue;
                }
                
                // 解析日期（Excel日期格式）
                Date obDate;
                try {
                    // 尝试解析Excel日期
                    if (obDateStr.matches("\\d+(\\.\\d+)?")) {
                        // Excel日期数字
                        double excelDate = Double.parseDouble(obDateStr);
                        obDate = DateUtil.getJavaDate(excelDate);
                    } else {
                        // 字符串日期
                        obDate = dateFormat.parse(obDateStr);
                    }
                } catch (Exception e) {
                    log.error("解析日期失败: {}", obDateStr, e);
                    successMsg += " 行 " + (k + 1) + " 日期格式错误，跳过.";
                    skipped++;
                    continue;
                }
                
                // 创建对账详情
                LxVndCheckDetails details = new LxVndCheckDetails();
                details.setVclId(vclId);
                details.setObDate(dateFormat.format(obDate));
                details.setObDateInt((int) (obDate.getTime() / 1000));
                details.setBlNo(blNo);
                details.setQty(qty);
                details.setTotalGw(BigDecimal.valueOf(totalGw));
                details.setPrice(BigDecimal.valueOf(price));
                
                // 报关费
                if (row.size() > 5 && !row.get(5).trim().isEmpty()) {
                    details.setBgFee(BigDecimal.valueOf(Double.parseDouble(row.get(5).trim())));
                }
                
                // 杂费
                if (row.size() > 6 && !row.get(6).trim().isEmpty()) {
                    details.setZfFee(BigDecimal.valueOf(Double.parseDouble(row.get(6).trim())));
                }
                
                // 抵扣费
                if (row.size() > 7 && !row.get(7).trim().isEmpty()) {
                    double dkFee = Double.parseDouble(row.get(7).trim());
                    if (dkFee > 0) {
                        details.setDkFee(BigDecimal.valueOf(dkFee));
                    }
                }
                
                // 备注
                if (row.size() > 8 && !row.get(8).trim().isEmpty()) {
                    details.setRemarks(row.get(8).trim());
                }
                
                // 是否确认
                if (row.size() > 9 && "是".equals(row.get(9).trim())) {
                    details.setIsCheck(1);
                } else {
                    details.setIsCheck(0);
                }
                
                // 计算总金额
                BigDecimal totalAmount = details.getPrice().multiply(details.getTotalGw());
                if (details.getBgFee() != null) {
                    totalAmount = totalAmount.add(details.getBgFee());
                }
                if (details.getZfFee() != null) {
                    totalAmount = totalAmount.add(details.getZfFee());
                }
                if (details.getDkFee() != null) {
                    totalAmount = totalAmount.subtract(details.getDkFee());
                }
                details.setTotalAmount(totalAmount);
                
                details.setAddUid(userId);
                details.setAddTime(currentTime);
                
                vndCheckDetailsMapper.insert(details);
                imported++;
            }
            
            // 更新对账列表的统计信息
            updateVndCheckListSummary(vclId);
            
            result.put("success", true);
            result.put("message", successMsg);
            result.put("imported", imported);
            result.put("skipped", skipped);
            
        } catch (Exception e) {
            log.error("导入Excel失败", e);
            result.put("message", "导入失败：" + e.getMessage());
        }
        
        return result;
    }
    
    @Override
    public List<Map<String, Object>> getVndMonthlyStatistics(Integer type, Integer year) {
        if (year == null) {
            // 默认当前年份
            year = java.util.Calendar.getInstance().get(java.util.Calendar.YEAR);
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("type", type);
        params.put("year", year);
        
        // 当前月份
        int currentMonth = java.util.Calendar.getInstance().get(java.util.Calendar.MONTH) + 1;
        params.put("currentMonth", currentMonth);
        
        return vndCheckListMapper.selectVndMonthlyStatistics(params);
    }
}
